﻿using Autodesk.Revit.UI;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Sunisoft.IrisSkin;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using RevitTest;
using ParamSettings;

namespace RevitAddin
{
    public partial class CableDataForm : Form
    {
        private drawLine drawLineCMD = null;
        private ExternalEvent drawLineEvent = null;
        private Lofting LoftCmd = null;
        private ExternalEvent LoftCmdEvent = null;

        public CableDataForm()
        {
            InitializeComponent();
            drawLineCMD = new drawLine();
            drawLineEvent = ExternalEvent.Create(drawLineCMD);

            LoftCmd = new Lofting();
            LoftCmdEvent = ExternalEvent.Create(LoftCmd);
        }

        private void CableDataForm_Load(object sender, EventArgs e)
        {
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                dgv.Rows.Clear();
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.CheckFileExists = true;
                ofd.Multiselect = false;
                ofd.InitialDirectory = comMethod.dirPath;
                ofd.RestoreDirectory = true;
                ofd.Filter = "csv文件|*.csv";

                string path = "";
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    path = ofd.FileName;
                    comMethod.dirPath = Path.GetDirectoryName(path);
                }
                else
                {
                    return;
                }

                pathTextBox.Text = path;
                List<CableData> CCIList = comMethod.NewReadCableContactItemExcel(pathTextBox.Text.Trim());

                for (int i = 0; i < CCIList.Count; i++)
                {

                    DataGridViewRow row = new DataGridViewRow();
                    row.CreateCells(this.dgv);
                    row.Cells[0].Value = CCIList[i].Id;
                    row.Cells[1].Value = string.IsNullOrEmpty(CCIList[i].CableStart) ? "" : CCIList[i].CableStart;
                    row.Cells[2].Value = string.IsNullOrEmpty(CCIList[i].CableNumber) ? "" : CCIList[i].CableNumber;
                    row.Cells[3].Value = string.IsNullOrEmpty(CCIList[i].CableEnd) ? "" : CCIList[i].CableEnd;
                    row.Cells[4].Value = CCIList[i].IsTop;
                    row.Cells[5].Value = CCIList[i].IsOneTwo;
                    row.Cells[6].Value = CCIList[i].IsOpposite;
                    row.Cells[7].Value = CCIList[i].IsHighTensionCable;
                    


                    dgv.Rows.Add(row);
                }

            }
            catch (Exception ee)
            {
                MessageBox.Show("出现异常请联系管理员" + ee.Message, "温馨提示");
            }
        }



        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton1.Checked)
            {
                UpdateSelectedRowsValue(true);
            }
        }

        private void UpdateSelectedRowsValue(bool value)
        {
            // 遍历选中的行
            foreach (DataGridViewRow row in dgv.SelectedRows)
            {
                int columnIndex = 4; // 替换为实际的“是否走顶部”列索引
                if (row.Cells[columnIndex] != null)
                {
                    row.Cells[columnIndex].Value = value; // 根据选择的值设置单元格内容
                }
            }

            // 如果表格绑定了数据源，需要刷新表格
            dgv.Refresh();
        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton2.Checked)
            {
                UpdateSelectedRowsValue(false);
            }
        }

        private void dgv_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            UpdateRadioButtonState();
        }

        // 更新单选按钮状态
        private void UpdateRadioButtonState()
        {
            if (dgv.SelectedRows.Count > 0)
            {
                var selectedRow = dgv.SelectedRows[0];

                // 更新“是否走顶部”状态
                UpdateRadioButtonGroup(selectedRow, 4, radioButton1, radioButton2);

                // 更新“是否走一二层”状态
                UpdateRadioButtonGroup(selectedRow, 5, radioButton4, radioButton3);

                // 更新“是否走对侧”状态
                UpdateRadioButtonGroup(selectedRow, 6, radioButton6, radioButton5);

                // 更新“是否为高压电缆”状态
                UpdateRadioButtonGroup(selectedRow, 7, radioButton8, radioButton7);
            }
        }
        // 更新单选按钮组状态的方法
        private void UpdateRadioButtonGroup(DataGridViewRow row, int columnIndex, RadioButton rbYes, RadioButton rbNo)
        {
            if (row.Cells[columnIndex]?.Value is bool value)
            {
                rbYes.Checked = value;
                rbNo.Checked = !value;
            }
        }

        private void dgv_SelectionChanged(object sender, EventArgs e)
        {
            UpdateRadioButtonState();

        }

        private void radioButton4_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton4.Checked)
            {
                // 遍历选中的行
                foreach (DataGridViewRow row in dgv.SelectedRows)
                {
                    int columnIndex = 5; // 替换为实际的“是否走顶部”列索引
                    if (row.Cells[columnIndex] != null)
                    {
                        row.Cells[columnIndex].Value = true; // 根据选择的值设置单元格内容
                    }
                }

                // 如果表格绑定了数据源，需要刷新表格
                dgv.Refresh();
            }
        }

        private void radioButton3_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton3.Checked)
            {
                // 遍历选中的行
                foreach (DataGridViewRow row in dgv.SelectedRows)
                {
                    int columnIndex = 5; // 替换为实际的“是否走顶部”列索引
                    if (row.Cells[columnIndex] != null)
                    {
                        row.Cells[columnIndex].Value = false; // 根据选择的值设置单元格内容
                    }
                }

                // 如果表格绑定了数据源，需要刷新表格
                dgv.Refresh();
            }
        }

        private void radioButton6_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton6.Checked)
            {
                // 遍历选中的行
                foreach (DataGridViewRow row in dgv.SelectedRows)
                {
                    int columnIndex = 6; // 替换为实际的“是否走顶部”列索引
                    if (row.Cells[columnIndex] != null)
                    {
                        row.Cells[columnIndex].Value = true; // 根据选择的值设置单元格内容
                    }
                }

                // 如果表格绑定了数据源，需要刷新表格
                dgv.Refresh();
            }
        }

        private void radioButton5_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton5.Checked)
            {
                foreach (DataGridViewRow row in dgv.SelectedRows)
                {
                    int columnIndex = 6; // 替换为实际的“是否走顶部”列索引
                    if (row.Cells[columnIndex] != null)
                    {
                        row.Cells[columnIndex].Value = false; // 根据选择的值设置单元格内容
                    }
                }

                // 如果表格绑定了数据源，需要刷新表格
                dgv.Refresh(); UpdateSelectedRowsValue(false);
            }
        }

        private async void button3_Click(object sender, EventArgs e)
        {
            // 文件保存路径
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Filter = "文本文件 (*.txt)|*.txt",
                Title = "保存数据文件"
            };

            // 获取项目根目录
            string projectRootDirectory = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;

            // 固定文件名
            string fileName = "requestData.txt";

            // 组合文件完整路径
            string filePath = Path.Combine(projectRootDirectory, fileName);

            try
            {
                using (StreamWriter sw = new StreamWriter(filePath, false, System.Text.Encoding.UTF8))
                {

                    // 写入文件名
                    sw.WriteLine($"FileName={Global.ModelName}");

                    // 遍历表格数据
                    foreach (DataGridViewRow row in dgv.Rows)
                    {
                        if (!row.IsNewRow) // 跳过空白新行
                        {
                            // 获取单元格数据
                            string cableStart = row.Cells["Column2"].Value?.ToString() ?? "";
                            string cableNumber = row.Cells["Column3"].Value?.ToString() ?? "";
                            string cableEnd = row.Cells["Column4"].Value?.ToString() ?? "";
                            string isTop = row.Cells["Column5"].Value?.ToString()?.ToLower() ?? "false";
                            string isOneTwo = row.Cells["Column6"].Value?.ToString()?.ToLower() ?? "false";
                            string isOpposite = row.Cells["Column7"].Value?.ToString()?.ToLower() ?? "false";
                            string isHighTensionCable = row.Cells["Column8"].Value?.ToString()?.ToLower() ?? "false";

                            // 格式化数据行
                            string line = $"cableStart={cableStart},cableNumber={cableNumber},cableEnd={cableEnd},isTop={isTop},isOneTwo={isOneTwo},isOpposite={isOpposite},isHighTensionCable={isHighTensionCable}";

                            // 写入行数据
                            sw.WriteLine(line);
                        }
                    }
                }
                // 从根目录读取文件
                string filePath1 = filePath;
                //string filePath1 = "E:\\Project data\\布线\\自动布线\\RevitAddin\\bin\\Debug\\requestData.txt";  // 文件路径
                //string filePath1 = "D:\\requestData.txt";  // 文件路径

                if (!File.Exists(filePath1))
                {
                    MessageBox.Show("请求文件不存在", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 读取文件内容
                string[] fileLines = File.ReadAllLines(filePath1);

                // 构造请求参数对象
                RequestPara requestPara = new RequestPara
                {
                    FileName = fileLines[0].Split('=')[1].Trim(),  // 第一行是文件名
                    ACList = new List<AutoConfig>()
                };

                // 从第二行开始解析请求参数
                for (int i = 1; i < fileLines.Length; i++)
                {
                    string[] parameters = fileLines[i].Split(',');

                    AutoConfig config = new AutoConfig
                    {
                        cableStart = parameters[0].Split('=')[1].Trim(),
                        cableNumber = parameters[1].Split('=')[1].Trim(),
                        cableEnd = parameters[2].Split('=')[1].Trim(),
                        isTop = bool.Parse(parameters[3].Split('=')[1].Trim()),
                        isOneTwo = bool.Parse(parameters[4].Split('=')[1].Trim()),
                        IsOpposite = bool.Parse(parameters[5].Split('=')[1].Trim()),
                        IsHighTensionCable = bool.Parse(parameters[6].Split('=')[1].Trim())
                    };

                    requestPara.ACList.Add(config);
                }

                // 使用 HttpClient 发出 HTTP Post 请求
                using (HttpClient httpClient = new HttpClient())
                {
                    // 将请求参数对象序列化为 JSON 格式
                    string jsonData = JsonConvert.SerializeObject(requestPara);//请求参数对象

                    // 发送请求数据包
                    StringContent content = new StringContent(jsonData, Encoding.UTF8);

                    // 设置 HTTP 请求的 Content-Type 为 application/json
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                    // 设置请求的访问地址
                    // 从配置或方法读取 API 路径
                    string url = ParamManager.getParamValue(globalVar.pathParam,"calculateAPI", "http://127.0.0.1:5001/AutoWiring/GetData"); 

                    // 发出 HTTP Post 请求
                    HttpResponseMessage response = await httpClient.PostAsync(url, content);

                    // 读取返回的响应内容
                    string responseContent = await response.Content.ReadAsStringAsync();

                    // 将响应内容反序列化为对象
                    ResponseResult<Dictionary<string, Dictionary<string, List<XYZ>>>> result = JsonConvert.DeserializeObject<ResponseResult<Dictionary<string, Dictionary<string, List<XYZ>>>>>(responseContent);

                    // 返回反序列化后的结果并在界面上显示
                    if (result != null && result.Code == HttpStatusCode.OK)
                    {
                        MessageBox.Show($"操作成功: {result.Message}", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show($"操作失败: {result?.Message ?? "无效响应"}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }

                drawLineEvent.Raise();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败：{ex.Message}", "保存失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


        }

        private async void button2_Click(object sender, EventArgs e)
        {

        }

        private void button4_Click(object sender, EventArgs e)
        {


        }

        private void button6_Click(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 放样
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            LoftCmdEvent.Raise();
        }

        private void radioButton8_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton8.Checked)
            {
                // 遍历选中的行
                foreach (DataGridViewRow row in dgv.SelectedRows)
                {
                    int columnIndex = 7; // 替换为实际的“是否走顶部”列索引
                    if (row.Cells[columnIndex] != null)
                    {
                        row.Cells[columnIndex].Value = true; // 根据选择的值设置单元格内容
                    }
                }

                // 如果表格绑定了数据源，需要刷新表格
                dgv.Refresh();
            }
        }

        private void radioButton7_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton7.Checked)
            {
                // 遍历选中的行
                foreach (DataGridViewRow row in dgv.SelectedRows)
                {
                    int columnIndex = 7; // 替换为实际的“是否走顶部”列索引
                    if (row.Cells[columnIndex] != null)
                    {
                        row.Cells[columnIndex].Value = false; // 根据选择的值设置单元格内容
                    }
                }

                // 如果表格绑定了数据源，需要刷新表格
                dgv.Refresh();
            }
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            comMethod.DisplayCableLengths(Global.resultDic, textBox1);
        }
    }
}
